import cv2
import numpy as np

if __name__ == '__main__':
    # 1. 读取图像
    image_np = cv2.imread('kun.jpg')


    # 2. 精准定义蓝色篮球的HSV范围（比BGR更易区分蓝色）
    hsv = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)
    lower_blue = np.array([90, 100, 100])
    upper_blue = np.array([140, 255, 255])
    blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)
    # 形态学处理优化掩膜（填充空洞、去除噪点）
    kernel = np.ones((5, 5), np.uint8)
    blue_mask = cv2.morphologyEx(blue_mask, cv2.MORPH_CLOSE, kernel)
    blue_mask = cv2.morphologyEx(blue_mask, cv2.MORPH_OPEN, kernel)

    # 3. 模板匹配（原逻辑）
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
    template = cv2.imread('basketball.jpg')
    h, w = template.shape[:2]
    template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
    res = cv2.matchTemplate(image_np_gray, template_gray, cv2.TM_CCOEFF_NORMED)
    threshold = 0.89
    loc = np.where(res > threshold)

    # 4. 绘制矩形时，跳过蓝色区域
    for x, y in zip(loc[1], loc[0]):
        # 检查该区域是否包含蓝色（通过蓝色掩膜判断）
        if not np.any(blue_mask[y:y+h, x:x+w]):
            cv2.rectangle(image_np, (x, y), (x + w, y + h), (0, 0, 255), thickness=2)

    # 5. 显示结果
    cv2.imshow('image_np', image_np)
    cv2.imwrite('without_blue.jpg', image_np)
    cv2.waitKey(0)
